// src/utils/request.js
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { getToken, removeToken, getRefreshToken, setToken } from '@/utils/auth'
import router from '@/router'

// 创建axios实例
const service = axios.create({
    baseURL: import.meta.env.VITE_APP_BASE_API,
    timeout: 10000
})

// 请求拦截器
service.interceptors.request.use(
    config => {
        // 添加Authorization头
        if (getToken()) {
            config.headers['Authorization'] = 'Bearer ' + getToken()
        }
        return config
    },
    error => {
        return Promise.reject(error)
    }
)

// 响应拦截器
service.interceptors.response.use(
    response => {
        // 处理token刷新
        if (response.data?.token) {
            setToken(response.data.token)
        }
        return response.data
    },
    async error => {
        const { response, config } = error

        // 401处理 - token过期
        if (response.status === 401 && !config._retry) {
            config._retry = true
            try {
                // 尝试刷新token
                const refreshToken = getRefreshToken()
                if (refreshToken) {
                    const { data } = await refreshToken(refreshToken)
                    setToken(data.token)
                    config.headers['Authorization'] = 'Bearer ' + data.token
                    return service(config)
                }
            } catch (e) {
                // 刷新失败，跳转登录
                removeToken()
                router.push('/login')
                ElMessage.error('会话已过期，请重新登录')
                return Promise.reject(e)
            }
        }

        // 403处理 - 无权限
        if (response.status === 403) {
            ElMessage.error(response.data?.message || '权限不足')
        }

        // 其他错误处理
        const errorMessage = response.data?.message ||
            error.message ||
            '请求失败'

        // 非登录页面显示错误
        if (!window.location.pathname.includes('/login')) {
            ElMessage.error(errorMessage)
        }

        return Promise.reject(error)
    }
)

export default service